package org.song.videoplayer;

import ohos.agp.animation.AnimatorProperty;
import ohos.agp.components.*;
import ohos.agp.components.element.PixelMapElement;
import ohos.agp.utils.Color;
import ohos.agp.utils.LayoutAlignment;
import ohos.agp.window.dialog.BaseDialog;
import ohos.agp.window.dialog.PopupDialog;
import ohos.app.Context;
import ohos.global.resource.NotExistException;
import ohos.global.resource.ResourceManager;
import ohos.global.resource.WrongTypeException;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by song on 2017/4/9.
 * Contact github.com/tohodog
 * diy自己的播放器,不需要写播放逻辑,只需设置各个状态下view的显示状态即可
 */
public class DemoQSVideoView extends QSVideoViewHelp {

    protected Image coverImageView;//封面
    protected DirectionalLayout bottomContainer;//底部栏
    protected DirectionalLayout topContainer;//顶部栏
    protected StackLayout loadingContainer;//初始化
    protected StackLayout errorContainer;//出错了显示的 重试
    protected StackLayout bufferingContainer;//缓冲

    protected List<Component> changeViews;//根据状态隐藏显示的view集合
    private Image imgLoading;
    private AnimatorProperty animator;

    public DemoQSVideoView(Context context) {
        this(context, null);
    }

    public DemoQSVideoView(Context context, AttrSet attrs) {
        this(context, attrs, "0");
    }

    public DemoQSVideoView(Context context, AttrSet attrs, String defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initView();
    }

    public void setUIWithStateAndMode() {
        setUIWithStateAndMode(STATE_NORMAL, currentMode);
    }

    @Override
    protected int getLayoutId() {
        return ResourceTable.Layout_video_view;
    }

    protected void initView() {
        bottomContainer = (DirectionalLayout) controlContainer.findComponentById(ResourceTable.Id_layout_bottom);
        topContainer = (DirectionalLayout) controlContainer.findComponentById(ResourceTable.Id_layout_top);
        bufferingContainer = (StackLayout) controlContainer.findComponentById(ResourceTable.Id_buffering_container);
        loadingContainer = (StackLayout) controlContainer.findComponentById(ResourceTable.Id_loading_container);
        imgLoading = (Image) controlContainer.findComponentById(ResourceTable.Id_img_loading);

        errorContainer = (StackLayout) controlContainer.findComponentById(ResourceTable.Id_error_container);

        coverImageView = (Image) controlContainer.findComponentById(ResourceTable.Id_cover);

        changeViews = new ArrayList<>();

        //会根据播放器状态而改变的view加进去
        changeViews.add(topContainer);
        changeViews.add(bottomContainer);
        changeViews.add(loadingContainer);
        changeViews.add(errorContainer);
        changeViews.add(coverImageView);
        changeViews.add(startButton);
        changeViews.add(progressBar);
    }

    //根据播放状态设置ui显示/隐藏,包括控制UI
    @Override
    protected void changeUiWithStateAndMode(int status, int mode) {
        switch (status) {
            case STATE_NORMAL:
                showChangeViews(coverImageView, startButton);//普通状态显示封面和播放按钮
                break;
            case STATE_PREPARING:
                showChangeViews(loadingContainer);//初始化状态显示loading
                startLoading();
                break;
            case STATE_PLAYING:
            case STATE_PAUSE:
            case STATE_AUTO_COMPLETE://显示 播放按钮  [底部] [顶部]
                showChangeViews(startButton,
                        mode >= MODE_WINDOW_FLOAT_SYS ? null : bottomContainer,
                        mode == MODE_WINDOW_FULLSCREEN ? topContainer : null);
                break;
            case STATE_ERROR://出错显示errorContainer
                showChangeViews(errorContainer);
                break;
        }
        updateViewImage(status, mode);
        floatCloseView.setVisibility(mode >= MODE_WINDOW_FLOAT_SYS ? Component.VISIBLE : Component.INVISIBLE);
        floatBackView.setVisibility(mode >= MODE_WINDOW_FLOAT_SYS ? Component.VISIBLE : Component.INVISIBLE);
    }

    private void startLoading() {
        if (animator == null) {
            animator = imgLoading.createAnimatorProperty();
            animator.rotate(360).setDuration(2000).setLoopedCount(15);
            imgLoading.setBindStateChangedListener(new BindStateChangedListener() {
                @Override
                public void onComponentBoundToWindow(Component component) {
                    animator.start();
                }

                @Override
                public void onComponentUnboundFromWindow(Component component) {

                }
            });
        } else {
            animator.cancel();
            animator.reset();
            animator.rotate(360).setDuration(2000).setLoopedCount(15).start();
        }
    }

    //隐藏控制UI
    @Override
    protected void dismissControlView(int status, int mode) {
        bottomContainer.setVisibility(Component.INVISIBLE);
        topContainer.setVisibility(Component.INVISIBLE);
        progressBar.setVisibility(Component.VISIBLE);
        if (status != STATE_AUTO_COMPLETE)
            startButton.setVisibility(Component.INVISIBLE);
        if (mode >= MODE_WINDOW_FLOAT_SYS)
            floatCloseView.setVisibility(Component.INVISIBLE);
        if (mode >= MODE_WINDOW_FLOAT_SYS)
            floatBackView.setVisibility(Component.INVISIBLE);
    }

    //缓冲
    @Override
    protected void onBuffering(boolean isBuffering) {
        mHandler.postTask(() -> bufferingContainer.setVisibility(isBuffering ? VISIBLE : INVISIBLE));
    }

    //根据播放器状态要显示的view
    protected void showChangeViews(Component... views) {
        for (Component v : changeViews) {
            if (v != null)
                v.setVisibility(INVISIBLE);
        }
        for (Component v : views) {
            if (v != null) {
                v.setVisibility(VISIBLE);
            }
        }
    }

    protected void updateViewImage(int status, int mode) {
        try {
            ResourceManager manager = getResourceManager();
            PixelMapElement pause_selector = new PixelMapElement(manager.getResource(ResourceTable.Media_jc_pause_normal));
            PixelMapElement play_selector = new PixelMapElement(manager.getResource(ResourceTable.Media_jc_play_normal));
            PixelMapElement shrink = new PixelMapElement(manager.getResource(ResourceTable.Media_jc_shrink));
            PixelMapElement enlarge = new PixelMapElement(manager.getResource(ResourceTable.Media_jc_enlarge));
            startButton.setImageElement(status == STATE_PLAYING ? pause_selector : play_selector);
            fullscreenButton.setImageElement(mode == MODE_WINDOW_FULLSCREEN ? shrink : enlarge);
        } catch (IOException | NotExistException e) {
            e.printStackTrace();
        }
    }

    public Image getCoverImageView() {
        return coverImageView;
    }

    //至此diy播放器逻辑就完成了 非常简单百来行代码 只是设置view的显示和隐藏,真的不用写逻辑

    //==============================================================================================
    //--------------------- 以下为辅助功能,不需要不用写实现--------------------------------------------
    //==============================================================================================

    public boolean isShowWifiDialog = true;

    //移动网络提示框
    @Override
    protected boolean showWifiDialog() {
        if (!isShowWifiDialog)
            return false;
        try {
            ResourceManager resourceManager = getContext().getResourceManager();
            String tips_not_wifi = resourceManager.getElement(ResourceTable.String_tips_not_wifi).getString();
            String tips_not_wifi_confirm = resourceManager.getElement(ResourceTable.String_tips_not_wifi_confirm).getString();
            String tips_not_wifi_cancel = resourceManager.getElement(ResourceTable.String_tips_not_wifi_cancel).getString();
            DialogHelper dialogHelper = DialogHelper.CreateDialog(getContext()).setContentText(tips_not_wifi);
            dialogHelper.setDialogSize(800, 500);
            dialogHelper.setPositiveButton(tips_not_wifi_confirm, commonDialog -> {
                commonDialog.hide();
                prepareMediaPlayer();
            });
            dialogHelper.setNegativeButton(tips_not_wifi_cancel, BaseDialog::hide);
            dialogHelper.showDialog();
        } catch (IOException | NotExistException | WrongTypeException e) {
            e.printStackTrace();
        }
        return true;
    }

    //双击执行什么
    @Override
    protected void doubleClick() {
        clickFull();
    }

    //弹出清晰度选择
    @Override
    protected void popDefinition(Component view, List<QSVideo> qsVideos, int index) {
        ComponentContainer popview = (ComponentContainer) LayoutScatter.getInstance(getContext()).
                parse(ResourceTable.Layout_pop_definition, new StackLayout(getContext()), false);
        VideoPopWindow videoPopWindow = new VideoPopWindow(getContext(), popview, qsVideos, index);
        videoPopWindow.setOnItemListener(new VideoPopWindow.OnItemListener() {
            @Override
            public void OnClick(int position) {
                switchVideo(position);
            }
        });
        videoPopWindow.setOnDismissListener(new VideoPopWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                startDismissControlViewTimer(1314);
            }
        });
        videoPopWindow.showTop(view);
        cancelDismissControlViewTimer();
    }

    protected PopupDialog mProgressDialog;
    protected ProgressBar mDialogProgressBar;
    protected Text tv_current;
    protected Text tv_duration;
    protected Text tv_delta;
    protected Image mDialogIcon;

    //调节进度框
    @Override
    protected boolean showProgressDialog(int delta, int position, int duration) {
        if (mProgressDialog == null) {
            Component localView = LayoutScatter.getInstance(getContext()).parse(ResourceTable.Layout_jc_dialog_progress, null, false);
            mDialogProgressBar = ((ProgressBar) localView.findComponentById(ResourceTable.Id_duration_progressbar));
            tv_current = ((Text) localView.findComponentById(ResourceTable.Id_tv_current));
            tv_duration = ((Text) localView.findComponentById(ResourceTable.Id_tv_duration));
            tv_delta = ((Text) localView.findComponentById(ResourceTable.Id_tv_delta));
            mDialogIcon = ((Image) localView.findComponentById(ResourceTable.Id_duration_image_tip));
            mProgressDialog = new PopupDialog(mAbilitySlice, null);
            mProgressDialog.setCustomComponent(localView);
            mProgressDialog.setSize(LayoutConfig.MATCH_CONTENT, LayoutConfig.MATCH_CONTENT);

        }
        if (!mProgressDialog.isShowing()) {
            mProgressDialog.showOnCertainPosition(LayoutAlignment.CENTER, 0, 0);
        }

        tv_delta.setText(String.format("%s%ss",
                (delta > 0 ? "+" : ""),
                delta / 1000));
        tv_current.setText(Util.stringForTime(position + delta) + "/");
        tv_duration.setText(Util.stringForTime(duration));
        mDialogProgressBar.setProgressValue((position + delta) * 100 / duration);
        if (delta > 0) {
            mDialogIcon.setImageAndDecodeBounds(ResourceTable.Media_jc_forward_icon);
        } else {
            mDialogIcon.setImageAndDecodeBounds(ResourceTable.Media_jc_backward_icon);
        }
        return true;
    }

    @Override
    protected boolean dismissProgressDialog() {
        if (mProgressDialog != null) {
            mProgressDialog.hide();
            mProgressDialog.destroy();
            mProgressDialog = null;
        }
        return true;
    }


    protected PopupDialog mVolumeDialog;
    protected ProgressBar mDialogVolumeProgressBar;
    protected Text mDialogVolumeTextView;
    protected Image mDialogVolumeImageView;

    //调节音量框
    @Override
    protected boolean showVolumeDialog(int nowVolume, int maxVolume) {

        if (mVolumeDialog == null) {
            Component localView = LayoutScatter.getInstance(getContext()).parse(ResourceTable.Layout_jc_dialog_volume, null, false);
            mDialogVolumeImageView = ((Image) localView.findComponentById(ResourceTable.Id_volume_image_tip));
            mDialogVolumeTextView = ((Text) localView.findComponentById(ResourceTable.Id_tv_volume));
            mDialogVolumeProgressBar = ((ProgressBar) localView.findComponentById(ResourceTable.Id_volume_progressbar));
            mDialogVolumeProgressBar.setMaxValue(maxVolume);

            mVolumeDialog = new PopupDialog(getContext(), null);
            mVolumeDialog.setCustomComponent(localView);
            mVolumeDialog.setBackColor(Color.TRANSPARENT);
            mVolumeDialog.setSize(LayoutConfig.MATCH_CONTENT, LayoutConfig.MATCH_CONTENT);
        }
        if (!mVolumeDialog.isShowing())
            mVolumeDialog.showOnCertainPosition(LayoutAlignment.TOP, 0, Util.dp2px(getContext(), currentMode == MODE_WINDOW_NORMAL ? 25 : 50));

        mDialogVolumeTextView.setText(String.valueOf(nowVolume));
        mDialogVolumeProgressBar.setProgressValue(nowVolume);

        return true;
    }

    @Override
    protected boolean dismissVolumeDialog() {
        if (mVolumeDialog != null) {
            mVolumeDialog.hide();
            mVolumeDialog.destroy();
            mVolumeDialog = null;
        }
        return true;
    }

    protected PopupDialog mBrightnessDialog;
    protected ProgressBar mDialogBrightnessProgressBar;
    protected Text mDialogBrightnessTextView;

    //调节亮度框
    @Override
    protected boolean showBrightnessDialog(int brightnessPercent, int max) {
        System.out.println("===showBrightnessDialog===>" + brightnessPercent);
        if (mBrightnessDialog == null) {
            Component localView = LayoutScatter.getInstance(getContext())
                    .parse(ResourceTable.Layout_jc_dialog_brightness, null, true);
            mDialogBrightnessTextView = ((Text) localView.findComponentById(ResourceTable.Id_text_brightness));
            mDialogBrightnessProgressBar = ((ProgressBar) localView.findComponentById(ResourceTable.Id_brightness_progressbar));
            mDialogBrightnessProgressBar.setMaxValue(max);

            mBrightnessDialog = new PopupDialog(mAbilitySlice, null);
            mBrightnessDialog.setCustomComponent(localView);
            mBrightnessDialog.setBackColor(Color.TRANSPARENT);
            mBrightnessDialog.setSize(LayoutConfig.MATCH_CONTENT, LayoutConfig.MATCH_CONTENT);
        }

        if (!mBrightnessDialog.isShowing()) {
            mBrightnessDialog.showOnCertainPosition(LayoutAlignment.TOP, 0, Util.dp2px(getContext(), currentMode == MODE_WINDOW_NORMAL ? 25 : 50));
        }

        mDialogBrightnessTextView.setText(String.valueOf(brightnessPercent));
        mDialogBrightnessProgressBar.setProgressValue(brightnessPercent);

        return true;
    }

    @Override
    protected boolean dismissBrightnessDialog() {
        if (mBrightnessDialog != null) {
            mBrightnessDialog.hide();
            mBrightnessDialog.remove();
            mBrightnessDialog.destroy();
            mBrightnessDialog = null;
        }

        return true;
    }

}
